﻿#include <QEvent>
#include "JZSelfLayout.h"

JZSelfLayout::JZSelfLayout(QObject *parent) : QObject(parent) 
{
    m_widget = nullptr;
    m_xOffset = m_yOffset = 0;
    m_alignment = Qt::AlignTop | Qt::AlignLeft;
}

void JZSelfLayout::setWidget(QWidget *widget) {
    if (m_widget && m_widget->parentWidget()) {
        m_widget->parentWidget()->removeEventFilter(this);
    }
    m_widget = widget;
    if (m_widget) 
    {
        Q_ASSERT(m_widget->parentWidget());
        m_widget->parentWidget()->installEventFilter(this);             
    }
}

void JZSelfLayout::setAlignment(Qt::Alignment alignment) {
    m_alignment = alignment;
    handleParentResize();   
}

void JZSelfLayout::setOffset(int xOffset, int yOffset) {
    m_xOffset = xOffset;
    m_yOffset = yOffset;
    handleParentResize();    
}

bool JZSelfLayout::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::Resize)
    {
        bool ret = QObject::eventFilter(watched, event);
        handleParentResize();
        return ret;
    }

    return QObject::eventFilter(watched, event);
}

void JZSelfLayout::handleParentResize() 
{
    if (!m_widget || !m_widget->parentWidget())
        return;

    auto parentWidget = m_widget->parentWidget();
    int parentWidth = parentWidget->width();
    int parentHeight = parentWidget->height();
    int newX = 0;
    int newY = 0;

    if (m_alignment & Qt::AlignLeft) {
        newX = 0 + m_xOffset;
    }
    else if (m_alignment & Qt::AlignHCenter) {
        newX = parentWidth / 2 - m_widget->width() / 2 + m_xOffset;
    }
    else if (m_alignment & Qt::AlignRight) {
        newX = parentWidth - m_widget->width() + m_xOffset;
    }

    if (m_alignment & Qt::AlignTop) {
        newY = 0 + m_yOffset;
    }
    else if (m_alignment & Qt::AlignVCenter) {
        newY = parentHeight / 2 - m_widget->height() / 2 + m_yOffset;
    }
    else if (m_alignment & Qt::AlignBottom) {
        newY = parentHeight - m_widget->height() + m_yOffset;
    }

    m_widget->move(newX, newY);    
}